# -*- coding:utf-8 -*-
"""

"""

import requests
import re
from bs4 import BeautifulSoup
import time
from WriteData import writedata


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_urls(url):
    urllist = []
    text = get_html_text(url)
    text = eval(text)
    data = text['posts']
    if not data:
        return urllist
    urls = [date['content'] for date in data]
    reg = re.compile(r'(posts/\d+)')
    for url in urls:
        url = re.search(reg, url)
        urllist.append('http://www.gongxiangcj.com/' + url.group())
    return urllist


def get_datas(url):
    text = get_html_text(url)
    print('{}页面获取中'.format(url))
    if not text:
        return None
    soup = BeautifulSoup(text, 'lxml')
    title = soup.select_one('.postsTitle').get_text()
    postText = str(soup.select_one('.postsText'))
    ctmie = soup.select('.postsTool span')[1].get_text()
    zhaiyao = soup.select_one('.postsAbstract').get_text()
    d = {"title": title, "postText": postText, "ctime": ctmie, "zhaiyao": zhaiyao}
    writedata(d)


def result():
    a = 1
    while a < 4:
        url = 'http://www.gongxiangcj.com/get_posts?page={}&post_type=2'
        url = url.format(a)
        urllist = get_urls(url)
        time.sleep(10)
        for url in urllist:
        #     with open('url.txt', 'a', encoding='utf-8') as f:
        #         f.write(url + '\n')
            get_datas(url)
            time.sleep(5)
        a += 1

result()

# with open('url.txt', encoding='utf-8') as f:
#     for x in f:
#         get_datas(x)
#         time.sleep(5)